package leetcode.templates.二分;

public class BinarySearch {
    // 二分查找算法
    public static void main(String[] args) {
        int[] nums = {-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 5;
        int index = binarySearch(nums, target);
        System.out.println(index);
    }

    /**
     * @param nums   [-1, 2, 4, 5, 6, 6, ...]首位无效
     * @param target
     * @return
     */
    public static int binarySearch(int[] nums, int target) {
        int n = nums.length;
        int left = 1, right = n - 1, pos = 0;
        while (left <= right) {
            int mid = right - (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
                pos = mid;
            } else {
                right = mid - 1;
            }
        }
        return pos;// 如果pos = 0，说明target比nums中所有元素都小
    }
}
